package cc.yiueil.config;

import cc.yiueil.handler.MyAuthFailHandler;
import cc.yiueil.handler.MyAuthSuccessHandler;
import cc.yiueil.handler.MyLogoutSuccessHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Slf4j
@Configuration
public class SecurityConfig {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, CorsConfigurationSource corsConfigurationSource, MyAuthSuccessHandler myAuthSuccessHandler, MyLogoutSuccessHandler myLogoutSuccessHandler, MyAuthFailHandler myAuthFailHandler) throws Exception {
        http
                .csrf().disable()
                .cors().configurationSource(corsConfigurationSource).and()
                .authorizeHttpRequests(requests -> requests
                        .antMatchers("/customLogin").permitAll() // 允许访问
                        .anyRequest().authenticated() // 其他所有请求都拦截
                )
                // 登入
                .formLogin(form -> form
                        .loginProcessingUrl("/customLogin")
                        .successHandler(myAuthSuccessHandler)
                        .failureHandler(myAuthFailHandler)
                )
                // 登出
                .logout(logout -> logout
                        .logoutSuccessHandler(myLogoutSuccessHandler)
                );
        return http.build();
    }
}
